package com.xiaotu.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

@Controller
public class FileController {
    @Value("${file.dripath}")
    private String driPath;

    //向文件上传页面跳转
    @GetMapping("/toUpload")
    public String toUpload() {
        return "upload";
    }
    //向文件下载页面跳转
    @GetMapping("/toDownload")
    public String toDownLoad(){
        return "download";
    }
    //文件上传管理
    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile multipartFile, Model model) {
        //获取文件名及后缀名
        String filename = multipartFile.getOriginalFilename();
        //重新生成文件名       剔除 "-"
        filename = UUID.randomUUID().toString().replaceAll("-", "") + filename.substring(filename.lastIndexOf("."));
        //指定上传文件本地存储目录,不存在则创建
        String dirpath = driPath;
        //用时间生成新的文件路径,防止文件过多
        Date date = new Date();
        dirpath +=  (date.getYear() + 1900) + "\\" + (date.getMonth() + 1) + "\\" + (date.getDate()) + "\\";
        File file = new File(dirpath);
        if (!file.exists()) {
            file.mkdirs();
        }
        try {
            multipartFile.transferTo(new File(dirpath+filename));
            System.out.println(dirpath+filename);
            //默认文件上传成功,并返回状态
            model.addAttribute("uploadStatus", "上传成功!");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("uploadStatus", "上传失败!");
        }
        //携带上传状态信息回调文件上传页面
        return "upload";
    }
    /*@GetMapping("/downloadFile")
    public ResponseEntity<byte[]> downLoadFile(String filename){
        //指定要下载文件的路径
        String dripath = driPath;
        //创建该文件对象
        File file = new File(dripath + File.separator + filename);
        //设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        //通知浏览器以下载方式打开
        httpHeaders.setContentDispositionFormData("attachment", filename);
        //定义以流的形式下载返回数据文件
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }*/
    //原来的无法对中文处理,添加处理中文编码的代码
    @GetMapping("/downloadFile")
    public ResponseEntity<byte[]> downLoadFile(HttpServletRequest request, String filename) throws Exception{
        //指定要下载文件的路径
        String dripath = driPath;
        //创建该文件对象
        File file = new File(dripath + File.separator + filename);
        //设置响应头
        HttpHeaders httpHeaders = new HttpHeaders();
        //通知浏览器以下载方式打开(下载前对文件名进行转码)
        filename = getFileName(request,filename);
        httpHeaders.setContentDispositionFormData("attachment", filename);
        //定义以流的形式下载返回数据文件
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }
    }
    public String getFileName(HttpServletRequest request,String filename) throws Exception{
        //IE不同版本User_Agent中的关键词
        String[] IEBrowserKeyWords = {"MSIE","Trident","Edge"};
        //获取请求头信息
        String userAgent = request.getHeader("User_Agent");
        for(String keyWord:IEBrowserKeyWords){
            if(userAgent.contains(keyWord)) {
                //IE内核浏览器,统一为UTF-8编码显示.并对转换的+进行更正
                return URLEncoder.encode(filename, "UTF-8").replace("+", "");
            }
        }
        //火狐等其他浏览器统一为ISO-8859-1编码显示
        return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
    }
}
